// 图片存储管理工具
export interface StoredImage {
  id: string
  name: string
  url: string
  type: string
  size: number
  uploadTime: number
  category: 'character' | 'evolution' | 'example' | 'other'
}

// 本地存储键名
const STORAGE_KEY = 'lanxiaozi_images'

// 获取所有存储的图片
export function getStoredImages(): StoredImage[] {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    return stored ? JSON.parse(stored) : []
  } catch (error) {
    console.error('获取存储图片失败:', error)
    return []
  }
}

// 保存图片到本地存储
export function saveImageToStorage(image: StoredImage): void {
  try {
    const images = getStoredImages()
    const existingIndex = images.findIndex(img => img.id === image.id)
    
    if (existingIndex >= 0) {
      images[existingIndex] = image
    } else {
      images.push(image)
    }
    
    localStorage.setItem(STORAGE_KEY, JSON.stringify(images))
  } catch (error) {
    console.error('保存图片失败:', error)
  }
}

// 删除存储的图片
export function deleteStoredImage(imageId: string): void {
  try {
    const images = getStoredImages()
    const filteredImages = images.filter(img => img.id !== imageId)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(filteredImages))
  } catch (error) {
    console.error('删除图片失败:', error)
  }
}

// 根据分类获取图片
export function getImagesByCategory(category: StoredImage['category']): StoredImage[] {
  return getStoredImages().filter(img => img.category === category)
}

// 将文件转换为Base64并保存
export function uploadAndSaveImage(
  file: File, 
  category: StoredImage['category'] = 'other'
): Promise<StoredImage> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const url = e.target?.result as string
        const image: StoredImage = {
          id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          name: file.name,
          url: url,
          type: file.type,
          size: file.size,
          uploadTime: Date.now(),
          category: category
        }
        
        saveImageToStorage(image)
        resolve(image)
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsDataURL(file)
  })
}

// 清理过期图片（可选，用于管理存储空间）
export function cleanupOldImages(daysOld: number = 30): void {
  try {
    const images = getStoredImages()
    const cutoffTime = Date.now() - (daysOld * 24 * 60 * 60 * 1000)
    const recentImages = images.filter(img => img.uploadTime > cutoffTime)
    
    localStorage.setItem(STORAGE_KEY, JSON.stringify(recentImages))
  } catch (error) {
    console.error('清理图片失败:', error)
  }
}

// 获取存储使用情况
export function getStorageInfo(): { count: number; totalSize: number; sizeInMB: number } {
  const images = getStoredImages()
  const totalSize = images.reduce((sum, img) => sum + img.size, 0)
  
  return {
    count: images.length,
    totalSize: totalSize,
    sizeInMB: Math.round(totalSize / (1024 * 1024) * 100) / 100
  }
} 